package com.ljt.springbootwebsocketdemo.orginType;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
@ServerEndpoint(value = "/channel/test")
public class TestChannel {
	private static final Logger LOGGER = LoggerFactory.getLogger(TestChannel.class);

    private Session session;

    /**
     * 请注意这两个onmessage方法，一个只能接收二进制（也就是BASE64），一个只能接受text类型，
     * 发请求的时候就要注意发送的格式是二进制还是t文本类型
     */
    // @OnMessage(maxMessageSize = 10)
    @OnMessage
    public void onMessage(byte[] message) throws UnsupportedEncodingException {
        String msg = new String(message, "utf-8");
        LOGGER.info("webSocket后台收到消息：" + msg);
        sendMessage(msg);
    }
    @OnMessage
    public void onMessage(String message) {
        LOGGER.info("webSocket后台收到消息：" + message);
        sendMessage(message);
    }

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig){
        LOGGER.info("新的连接,id={}",session.getId());
        session.setMaxIdleTimeout(0);
        this.session = session;
    }

    @OnClose
    public void onClose(CloseReason closeReason){
        LOGGER.info("连接断开,id={} reason={}",this.session.getId(),closeReason);
    }

    @OnError
    public void onError(Throwable throwable) throws IOException {
        LOGGER.info("连接异常,id={},throwable={}",this.session.getId(),throwable);
        this.session.close();
        throwable.printStackTrace();
    }

    /**
     * 封装一个函数：发送消息给客户端
     */
    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText("你发送了："+message);
        } catch (IOException e) {
            LOGGER.error("发送消息失败", e);
        }
    }
}